package com.roads.site.controller;

import com.roads.common.annotation.Log;
import com.roads.common.config.MasterConfig;
import com.roads.common.constant.Constants;
import com.roads.common.constant.UserConstants;
import com.roads.common.core.controller.BaseController;
import com.roads.common.core.domain.AjaxResult;
import com.roads.common.core.domain.FileEntity;
import com.roads.common.core.page.TableDataInfo;
import com.roads.common.enums.BusinessType;
import com.roads.common.utils.DateUtils;
import com.roads.common.utils.SecurityUtils;
import com.roads.common.utils.StringUtils;
import com.roads.common.utils.file.FileUploadUtils;
import com.roads.common.utils.file.FileUtils;
import com.roads.common.utils.file.MimeTypeUtils;
import com.roads.common.utils.poi.ExcelUtils;
import com.roads.site.domain.SiteLabourStaffSalaryAnnex;
import com.roads.site.domain.SiteLabourStaffSalaryDetail;
import com.roads.site.domain.SiteLabourStaffSalaryMaster;
import com.roads.site.service.ISiteLabourStaffSalaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 劳务工工资Controller
 *
 * @author nhp
 * @date 2022-11-15
 */
@RestController
@RequestMapping("/labour/staff/salary")
public class SiteLabourStaffSalaryController extends BaseController {

    @Autowired
    private ISiteLabourStaffSalaryService salaryService;

    /**
     * 查询列表
     */
    @PreAuthorize("@ss.hasPermi('labour:salary:list')")
    @GetMapping("/masterList")
    public TableDataInfo masterList(SiteLabourStaffSalaryMaster model) {
        startPage();
        List<SiteLabourStaffSalaryMaster> list = salaryService.selectMasterModelList(model);
        return getDataTable(list);
    }

    /**
     * 查询明细列表
     */
    @PreAuthorize("@ss.hasPermi('labour:salary:list')")
    @GetMapping("/detailList")
    public TableDataInfo detailList(SiteLabourStaffSalaryDetail model) {
        startPage();
        List<SiteLabourStaffSalaryDetail> list = salaryService.selectDetailModelList(model);
        return getDataTable(list);
    }

    /**
     * 新增
     */
    @PreAuthorize("@ss.hasPermi('labour:salary:add')")
    @Log(title = "劳务工-工资发放", businessType = BusinessType.INSERT)
    @PostMapping("/addMaster")
    public AjaxResult addMaster(@RequestBody SiteLabourStaffSalaryMaster model) {
        // 查看本月是否添加
        if (StringUtils.isNotEmpty(model.getSalaryDate()) && UserConstants.NOT_UNIQUE.equals(salaryService.checkSalaryDateUnique(model))) {
            return AjaxResult.error("新增失败，" + model.getSalaryDate()  + "已存在");
        }
        return toAjax(salaryService.addMaster(model));
    }

    /**
     * 新增明细
     */
    @PreAuthorize("@ss.hasPermi('labour:salary:add')")
    @Log(title = "劳务工-工资明细", businessType = BusinessType.INSERT)
    @PostMapping("/addDetail")
    public AjaxResult addDetail(@RequestBody SiteLabourStaffSalaryDetail model) {
        return toAjax(salaryService.addDetail(model));
    }

    /**
     * 获取劳务工工资详情
     *
     * @param id 主键
     * @return 结果
     */
    @GetMapping(value = "/getMaster/{id}")
    public AjaxResult getMaster(@PathVariable("id") Integer id) {
        return AjaxResult.success(salaryService.getMaster(id));
    }

    /**
     * 获取劳务工工资明细详情
     *
     * @param id 主键
     * @return 结果
     */
    @GetMapping(value = "/getDetail/{id}")
    public AjaxResult getDetail(@PathVariable("id") Integer id) {
        return AjaxResult.success(salaryService.getDetail(id));
    }

    /**
     * 修改劳务工工资发放
     */
    @PreAuthorize("@ss.hasPermi('labour:salary:edit')")
    @Log(title = "劳务工-工资发放", businessType = BusinessType.UPDATE)
    @PutMapping("/updateMaster")
    public AjaxResult updateMaster(@RequestBody SiteLabourStaffSalaryMaster model) {
        if (StringUtils.isNotEmpty(model.getSalaryDate()) && UserConstants.NOT_UNIQUE.equals(salaryService.checkSalaryDateUnique(model))) {
            return AjaxResult.error("修改失败，" + model.getSalaryDate()  + "已存在");
        }
        model.setUpdateBy(getUsername());
        model.setUpdateTime(DateUtils.getNowDate());
        return toAjax(salaryService.updateMaster(model));
    }

    /**
     * 修改劳务工工资发放
     */
    @PreAuthorize("@ss.hasPermi('labour:salary:edit')")
    @Log(title = "劳务工-工资明细", businessType = BusinessType.UPDATE)
    @PutMapping("/updateDetail")
    public AjaxResult updateDetail(@RequestBody SiteLabourStaffSalaryDetail model) {
        model.setUpdateBy(getUsername());
        model.setUpdateTime(DateUtils.getNowDate());
        return toAjax(salaryService.updateDetail(model));
    }

    /**
     * 删除
     */
    @PreAuthorize("@ss.hasPermi('labour:salary:remove')")
    @Log(title = "劳务工-工资发放", businessType = BusinessType.DELETE)
    @DeleteMapping("/deleteMaster/{ids}")
    public AjaxResult deleteMaster(@PathVariable Integer[] ids) {
        return toAjax(salaryService.deleteMaster(ids));
    }

    /**
     * 删除明细
     */
    @PreAuthorize("@ss.hasPermi('labour:salary:remove')")
    @Log(title = "劳务工-工资明细", businessType = BusinessType.DELETE)
    @DeleteMapping("/deleteDetail/{ids}")
    public AjaxResult deleteDetail(@PathVariable Integer[] ids) {
        return toAjax(salaryService.deleteDetail(ids));
    }

    /**
     * 下载模板
     *
     * @return 模板
     */
    @GetMapping("/downloadTemplate")
    public AjaxResult downloadTemplate() {
        ExcelUtils<SiteLabourStaffSalaryDetail> utils = new ExcelUtils<>(SiteLabourStaffSalaryDetail.class);
        return utils.importTemplateExcel("劳务工工资导入模板");
    }

    /**
     * 导入数据
     *
     * @param file 文件
     * @param updateSupport 是否覆盖更新
     * @param masterId 主表主键
     * @return 导入结果
     */
    @Log(title = "劳务工-工资明细", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('labour:salary:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport, Integer masterId) {
        AjaxResult ajaxResult = new AjaxResult();
        ExcelUtils<SiteLabourStaffSalaryDetail> utils = new ExcelUtils<>(SiteLabourStaffSalaryDetail.class);
        List<SiteLabourStaffSalaryDetail> list = null;
        try {
            list = utils.importExcel(file.getInputStream());
            if (StringUtils.isNull(list) || list.size() == 0) {
                ajaxResult.put("status", "error");
                ajaxResult.put("msg", "导入数据不能为空");
                return ajaxResult;
            }
            ajaxResult = salaryService.importData(list, updateSupport, masterId);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxResult.put("status", "error");
            ajaxResult.put("msg", e.getMessage());
            return ajaxResult;
        }
        return ajaxResult;
    }

    /**
     * 附件列表集合
     *
     * @param uuid uuid
     * @return 附件集合
     */
    @GetMapping("/getAnnexList")
    public AjaxResult getAnnexList(String uuid) {
        SiteLabourStaffSalaryAnnex search = new SiteLabourStaffSalaryAnnex();
        search.setUuid(uuid);
        List<SiteLabourStaffSalaryAnnex> list = salaryService.selectAnnexList(search);
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.put("list", list);
        ajaxResult.put("annexCount", list.size());
        return ajaxResult;
    }

    /**
     * 附件上传
     *
     * @param file 文件
     * @param uuid uuid
     * @return 结果
     * @throws Exception 异常
     */
    @Log(title = "劳务工-工资附件", businessType = BusinessType.IMPORT)
    @PostMapping("/uploadAnnexFile")
    public AjaxResult uploadAnnexFile(MultipartFile file, String uuid) throws Exception {
        int result = 0;
        try{
            String annexPath = MasterConfig.getLabourStaffSalaryPath() + "/" + uuid;
            String fileName = file.getOriginalFilename();
            FileEntity fileEntity = FileUploadUtils.annexUpload(annexPath, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
            String filePath = fileEntity.getFilePath();
            String rename = filePath.substring(filePath.lastIndexOf("/") + 1);
            SiteLabourStaffSalaryAnnex annexFile = new SiteLabourStaffSalaryAnnex();
            annexFile.setRefilename(rename);
            annexFile.setFileName(fileName);
            if (fileEntity.getImage()) {
                annexFile.setIsImg(Constants.YES);
            } else {
                annexFile.setIsImg(Constants.NO);
            }
            annexFile.setFilePath(filePath);
            annexFile.setUuid(uuid);
            annexFile.setCreateBy(SecurityUtils.getUsername());
            annexFile.setCreateTime(DateUtils.getNowDate());
            result = salaryService.insertAnnex(annexFile, uuid);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.success(result);
    }

    /**
     * 附件下载
     *
     * @param fileId 文件ID
     * @param response 响应
     * @param request 请求
     */
    @GetMapping("/downloadAnnexFile")
    public void downloadAnnexFile(Long fileId, HttpServletResponse response, HttpServletRequest request) {
        try {
            SiteLabourStaffSalaryAnnex file = salaryService.getAnnex(fileId);
            String fileName = file.getFileName();
            String filePath = MasterConfig.getLabourStaffSalaryPath()
                    + "/" + file.getUuid() + "/"  + file.getRefilename();
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, fileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Log(title = "劳务工-工资附件", businessType = BusinessType.DELETE)
    @GetMapping("/deleteAnnexFile")
    public AjaxResult deleteAnnexFile(Long fileId) {
        SiteLabourStaffSalaryAnnex file = salaryService.getAnnex(fileId);
        String filePath = MasterConfig.getLabourStaffSalaryPath()
                + "/" + file.getUuid()
                + "/"  + file.getRefilename();
        FileUtils.deleteFile(filePath);
        int result = salaryService.deleteAnnex(fileId);
        return AjaxResult.success(result);
    }

}
